package com.osell.selection.ui.common;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.da.lon.wang.xlg.MyApplication;
import com.da.lon.wang.xlg.R;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.AgentWebSettingsImpl;
import com.osell.selection.ui.base.BaseActivity;
import com.osell.selection.ui.main.MainActivity;
import com.osell.selection.util.DeviceUuidFactory;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.HttpUrl;

public class WebViewActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.btn_back)
    ImageButton btn_back;
    @BindView(R.id.rl_top_bar)
    RelativeLayout rl_top_bar;
    @BindView(R.id.btn_top_bar_left)
    ImageButton btn_top_bar_left;
    @BindView(R.id.tv_top_bar_title)
    TextView tv_top_bar_title;
    @BindView(R.id.web_view_container)
    LinearLayout web_view_container;

    private AgentWeb mAgentWeb;

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //do your work
            if (url.contains("Member-index")) {
                startActivity(new Intent(view.getContext(), MainActivity.class)
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK));
            }
        }
    };

    private WebChromeClient mWebChromeClient = new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            //do your work
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            tv_top_bar_title.setText(title);
            tv_top_bar_title.requestFocus();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        ButterKnife.bind(this);

        btn_back.setOnClickListener(this);
        btn_top_bar_left.setOnClickListener(this);

        if (getIntent().getBooleanExtra("hide_top_bar", false)) {
            btn_back.setVisibility(View.VISIBLE);
            rl_top_bar.setVisibility(View.GONE);
        }

        String deviceId = new DeviceUuidFactory(MyApplication.getInstance()).getDeviceUuid().toString();
        String language = MyApplication.getInstance().getResources().getConfiguration().locale.getLanguage();
        if (TextUtils.equals("zh", language)) {
            language = "cn";
        }
        HttpUrl httpUrl = HttpUrl.parse(getIntent().getStringExtra("url"));
        mAgentWeb = AgentWeb.with(this) // 传入Activity
                .setAgentWebParent(web_view_container,
                        new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.MATCH_PARENT)) // 传入AgentWeb的父控件
                .useDefaultIndicator() // 使用默认进度条
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setAgentWebWebSettings(new AgentWebSettingsImpl() {
                    @Override
                    public WebSettings getWebSettings() {
                        WebSettings webSettings = super.getWebSettings();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            webSettings.setAllowFileAccessFromFileURLs(true);
                            webSettings.setAllowUniversalAccessFromFileURLs(true);
                        }
                        return webSettings;
                    }
                })
                .createAgentWeb()
                .ready()
                .go(httpUrl == null ? "" : httpUrl
                        .newBuilder()
                        .addQueryParameter("id", mUserInfoSp.getString("user_id", ""))
                        .addQueryParameter("user_id", mUserInfoSp.getString("user_id", ""))
                        .addQueryParameter("user_key", mUserInfoSp.getString("user_key", ""))
                        .addQueryParameter("deviceId", deviceId)
                        .addQueryParameter("deviceType", "1")
                        .addQueryParameter("device_id", deviceId)
                        .addQueryParameter("device_type", "1")
                        .addQueryParameter("lan", language)
                        .build()
                        .toString());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return mAgentWeb.handleKeyEvent(keyCode, event) || super.onKeyDown(keyCode, event);
    }

    @Override
    public void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        mAgentWeb.getWebLifeCycle().onDestroy();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (!mAgentWeb.back()) {
            super.onBackPressed();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back:
            case R.id.btn_top_bar_left:
                onBackPressed();
                break;
        }
    }
}
